package com.moudle.app.fragment;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.moudle.app.AppConfig;
import com.moudle.app.AppContext;
import com.moudle.app.R;
import com.moudle.app.base.BaseFragMent;
import com.moudle.app.ui.SimpleBackActivity;
import com.moudle.app.widget.EmptyLayout;

/**
 * @Description 浏览器fragment, 就通过webview加载url
 * @Author Li Chao
 * @Date 2015/12/31 16:36
 */
public class BrowserFragment extends BaseFragMent  {
    protected WebView mWebView;
    protected EmptyLayout mEmptyLayout;
    public final static String DEFAULT = "http://www.moudle.com/";
    public final static String BROWSER_KEY = "browser_url";
    private String mCurrentUrl = DEFAULT;
    private CookieManager cookie;
    private Activity mAty;
    private View mHeadView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View v = inflater.inflate(R.layout.activity_pull_webview, container, false);
        mAty = getActivity();
        // 初始化界面
        initData();
        initView(v);
        return v;
    }

    @Override
    public void initData() {
        Bundle bundle = getArguments();//暂时只传一个url
        //以后，传进来一个标识，根据标识把传过来的serialize进行强转相应对象，再进行一系列的webview的设置
        if (bundle != null) {
            mCurrentUrl = bundle.getString(BROWSER_KEY);
        }
    }

    @Override
    public void initView(View v) {
        mEmptyLayout = (EmptyLayout) v.findViewById(R.id.error_layout);
        mEmptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                mWebView.reload();
            }
        });
        initWebView();
    }

    /**
     * 初始化浏览器设置信息
     */
    private void initWebView() {
        cookie = CookieManager.getInstance();
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true); // 启用支持javascript
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);// 优先使用缓存
        //webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存
        webSettings.setAllowFileAccess(true);// 可以访问文件
        webSettings.setBuiltInZoomControls(true);// 支持缩放
        if (android.os.Build.VERSION.SDK_INT >= 11) {
            webSettings.setPluginState(WebSettings.PluginState.ON);
            webSettings.setDisplayZoomControls(false);// 支持缩放
        }
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.loadUrl(mCurrentUrl);
    }


    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            onWebTitle(view, title);
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            super.onReceivedIcon(view, icon);
            onWebIcon(view, icon);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) { // 进度
            super.onProgressChanged(view, newProgress);
            if (newProgress > 90 && getApplication().isNetworkConnected()) {
                mEmptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
            }
        }
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            onUrlLoading(view, url);
            boolean flag = super.shouldOverrideUrlLoading(view, url);
            mCurrentUrl = url;
            return flag;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            onUrlFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            if (errorCode == -2) {//无可用网络
                mWebView.stopLoading();
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
            }
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    }

    /**
     * 链接载入成功后会被调用
     *
     * @param view WebView
     * @param url  链接地址
     */
    protected void onUrlFinished(WebView view, String url) {
        mCurrentUrl = url;
    }

    /**
     * 载入链接之前会被调用
     *
     * @param view WebView
     * @param url  链接地址
     */
    protected void onUrlLoading(WebView view, String url) {
        cookie.setCookie(url,
                AppContext.getInstance().getProperty(AppConfig.CONF_COOKIE));
    }

    /**
     * 当前WebView显示页面的标题
     *
     * @param view  WebView
     * @param title web页面标题
     */
    protected void onWebTitle(WebView view, String title) {
        if (mAty != null && mWebView != null) { // 必须做判断，由于webview加载属于耗时操作，可能会本Activity已经关闭了才被调用
//            ((TextView) mHeadView.findViewById(R.id.acitivity_name)).setText(mWebView.getTitle());//TODO 以后根据业务是否是传Url还是serialize，目前是传Url
            //((BaseActivity) mAty).setActionBarTitle(mWebView.getTitle());
        }
    }

    /**
     * 当前WebView显示页面的图标
     *
     * @param view WebView
     * @param icon web页面图标
     */
    protected void onWebIcon(WebView view, Bitmap icon) {
    }

    @Override
    public void onResume() {
        super.onResume();
        mWebView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mWebView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mWebView.destroy();
    }

}
